package com.dimples.wxpush.helper;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.dimples.wxpush.constant.ConfigConstant;
import com.dimples.wxpush.utils.HttpUtils;
import com.dimples.wxpush.utils.JsonObjectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2024/11/16
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WxHelper {

    private final ConfigConstant configConstant;


    /**
     * 计算生日
     *
     * @param birthday 出生日期
     * @param date     当前时间
     * @return JSONObject
     */
    public static JSONObject getBirthday(String birthday, String date) {
        return JsonObjectUtil.packJsonObject(getBirthdayDay(birthday, date) + "天", "#6EEDE2");
    }

    public static String getBirthdayDay(String birthday, String date) {
        String birthDay;
        Calendar calendar = Calendar.getInstance();
        String newD = calendar.get(Calendar.YEAR) + "-" + birthday;
        birthDay = StrUtil.toStringOrNull(DateUtil.betweenDay(DateUtil.parseDateTime(date), DateUtil.parseDateTime(newD), true));
        if (Integer.parseInt(birthDay) < 0) {
            Integer newBirthDay = Integer.parseInt(birthDay) + 365;
            birthDay = String.valueOf(newBirthDay);
        }
        return birthDay;
    }

    /**
     * 计算农历生日
     */
    private JSONObject getLunarBirthday(String birthday, String date) {
        return JsonObjectUtil.packJsonObject(getLunarBirthdayDay(birthday, date) + "天", "#6EEDE2");
    }

    private String getLunarBirthdayDay(String birthday, String date) {
        String daysUntilNextLunarBirthday = "";
        try {
            // 将农历生日转换为当年的日期
            LocalDate lunarBirthday = LocalDate.parse("2023-" + birthday);
            // 将当天日期转换为LocalDate对象
            LocalDate currentDate = LocalDate.parse(date);

            // 如果当前日期已经过了农历生日，则计算下一年的农历生日
            if (currentDate.isAfter(lunarBirthday)) {
                lunarBirthday = lunarBirthday.plusYears(1);
            }

            // 计算距离下一次农历生日的天数
            daysUntilNextLunarBirthday = StrUtil.toStringOrNull(ChronoUnit.DAYS.between(currentDate, lunarBirthday));
        } catch (Exception e) {
            log.error("生日计算错误，请检测格式" + e.getMessage());
        }
        return daysUntilNextLunarBirthday;
    }

    /**
     * 计算在一起的天数
     *
     * @param date String
     * @return JSONObject
     */
    public JSONObject togetherDay(String date) {
        //在一起时间
        String togetherDay = "";
        togetherDay = "第" + DateUtil.betweenDay(DateUtil.parseDateTime(configConstant.getTogetherDate()), DateUtil.parseDateTime(date), true) + "天";
        return JsonObjectUtil.packJsonObject(togetherDay, "#FEABB5");
    }

    /**
     * 天气含“雨”,设置为蓝色
     *
     * @param s String
     * @return String
     */
    public static String isContainsRain(String s) {
        return s.contains("雨") ? "#1f95c5" : "#b28d0a";
    }

    /**
     * 给公众号推送消息
     *
     * @param accessToken accessToken
     * @param errorList   List<JSONObject>
     * @param resultMap   HashMap<String, Object>
     * @param opedId      String
     */
    public JSONObject sendMessage(String accessToken, List<JSONObject> errorList, HashMap<String, Object> resultMap, String opedId) {
        JSONObject templateMsg = new JSONObject(new LinkedHashMap<>());
        templateMsg.put("touser", opedId);
        templateMsg.put("template_id", configConstant.getTemplateId());
        templateMsg.put("data", new JSONObject(resultMap));
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;

        String sendPost = HttpUtils.sendPost(url, templateMsg.toJSONString());
        JSONObject WeChatMsgResult = JSONObject.parseObject(sendPost);
        if (!"0".equals(WeChatMsgResult.getString("errcode"))) {
            JSONObject error = new JSONObject();
            error.put("openid", opedId);
            error.put("errorMessage", WeChatMsgResult.getString("errmsg"));
            errorList.add(error);
        }
        return templateMsg;
    }
}
